package org.raymond.iworks.study.orders.schedule;

import lombok.extern.slf4j.Slf4j;
import org.raymond.iworks.study.orders.common.GlobalCache;
import org.raymond.iworks.study.orders.entity.TInventoriesSeckillBook;
import org.raymond.iworks.study.orders.repository.TInventorySeckillBookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedTransferQueue;

@Slf4j
@Configuration
public class ScheduleTaskConfig implements SchedulingConfigurer {
    @Autowired
    private TInventorySeckillBookRepository tInventorySeckillBookRepository;
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        List<TInventoriesSeckillBook> bookList = new ArrayList<>();
        taskRegistrar.addCronTask(()->{
            LinkedTransferQueue<TInventoriesSeckillBook> queue = GlobalCache.instance().getSeckillQueue();
            if(queue!=null && !queue.isEmpty()) {
                queue.drainTo(bookList);
            }
            int size = bookList.size();
            if(size>0) {
                tInventorySeckillBookRepository.saveAllAndFlush(bookList);
                bookList.clear();
            }
        }, "* * * * * ?");
    }
}
